package controllers

import (
	"encoding/json"
	beego "github.com/beego/beego/v2/server/web"
	"gorm.io/gorm"
	"one/models"
	"path/filepath"
	"strconv"
)

type DrugController struct {
	beego.Controller
}
type JsonR struct {
	Code int         `json:"code"`
	Msg  string      `json:"msg"`
	Data interface{} `json:"data"`
}

func (c *DrugController) Get() {

}
func (c *DrugController) Add() {

	name := c.GetString("name")
	age, _ := c.GetInt("age")
	sex := c.GetString("sex")
	img := c.GetString("img")
	drug := models.Drug{
		Name: name,
		Age:  age,
		Sex:  sex,
		Img:  img,
	}
	if name == "" || sex == "" || age == 0 {
		c.Data["json"] = JsonR{
			Code: 0,
			Msg:  "数据不能为空",
			Data: nil,
		}
		c.ServeJSON()
		return
	}
	err := models.DB.Create(&drug).Error
	if err != nil {
		c.Data["json"] = JsonR{
			Code: 0,
			Msg:  "添加失败",
			Data: nil,
		}
		c.ServeJSON()
		return
	} else {
		c.Data["json"] = JsonR{
			Code: 200,
			Msg:  "添加成功",
			Data: drug,
		}
		c.ServeJSON()
	}
}
func (c *DrugController) Upload() {
	file, header, err := c.GetFile("img")
	if err != nil {
		c.Data["json"] = JsonR{
			Code: 0,
			Msg:  "文件获取失败",
			Data: nil,
		}
		c.ServeJSON()
		return
	}
	defer file.Close()
	ext := map[string]bool{
		".png":  true,
		".jpeg": true,
	}
	suffix := filepath.Ext(header.Filename)
	if !ext[suffix] {
		c.Data["json"] = JsonR{
			Code: 0,
			Msg:  "文件类型错误",
			Data: nil,
		}
		c.ServeJSON()
		return
	}

	if header.Size > 2*1024*1024 {
		c.Data["json"] = JsonR{
			Code: 0,
			Msg:  "文件过大 请重新上传",
			Data: nil,
		}
		c.ServeJSON()
		return
	}
	path := "static/img" + header.Filename
	err = c.SaveToFile("img", path)
	if err != nil {
		c.Data["json"] = JsonR{
			Code: 0,
			Msg:  "文件上传失败",
			Data: nil,
		}
		c.ServeJSON()
		return
	} else {
		c.Data["json"] = JsonR{
			Code: 200,
			Msg:  "文件上传成功",
			Data: "http://127.0.0.1:8080/" + path,
		}
		c.ServeJSON()
	}
}
func (c *DrugController) List() {
	page, _ := c.GetInt("page", 1)
	size, _ := c.GetInt("size", 5)
	pageData := make(map[string]interface{})
	key := "page-" + strconv.Itoa(page)
	val, err := models.Rdb.Get(key).Result()

	if err != nil {
		var count int64
		offest := (page - 1) * size
		var drug []models.Drug
		query := models.DB.Model(&models.Drug{})
		query.Count(&count)
		name := c.GetString("name")
		if name != "" {
			query = query.Where("name like?", "%"+name+"%")
		}
		err = models.DB.Offset(offest).Limit(size).Find(&drug).Error

		if err != nil {
			c.Data["json"] = JsonR{
				Code: 0,
				Msg:  "查询失败",
				Data: nil,
			}
			c.ServeJSON()
			return
		} else {
			pageData["count"] = count
			pageData["drugs"] = drug
			marshal, _ := json.Marshal(&pageData)
			value := string(marshal)
			models.Rdb.Set(key, value, 0)
			c.Data["json"] = JsonR{
				Code: 200,
				Msg:  "查询成功-mysql",
				Data: pageData,
			}
			c.ServeJSON()

		}
	} else {
		json.Unmarshal([]byte(val), &pageData)
		c.Data["json"] = JsonR{
			Code: 200,
			Msg:  "查询成功-redis",
			Data: pageData,
		}
		c.ServeJSON()
	}
}
func (c *DrugController) Del() {

}
func (c *DrugController) Info() {

	var drug models.Drug
	id, _ := c.GetInt("id")
	key := "drug-rank" + strconv.Itoa(id)
	val, err := models.Rdb.Get(key).Result()
	xx := "drug-phb"
	if err != nil {
		err = models.DB.Where("id=?", id).First(&drug).Error
		if err != nil {
			c.Data["json"] = JsonR{
				Code: 0,
				Msg:  "详情展示失败",
				Data: nil,
			}
			c.ServeJSON()
			return
		} else {
			models.Rdb.ZIncrBy(xx, 1, drug.Name)
			marshal, _ := json.Marshal(&drug)
			value := string(marshal)
			models.Rdb.Set(key, value, 0)
			c.Data["json"] = JsonR{
				Code: 200,
				Msg:  "详情展示成功-mysql",
				Data: drug,
			}
			c.ServeJSON()
		}
	} else {
		json.Unmarshal([]byte(val), &drug)
		models.Rdb.ZIncrBy(xx, 1, drug.Name)
		c.Data["json"] = JsonR{
			Code: 200,
			Msg:  "详情展示成功-redis",
			Data: drug,
		}
		c.ServeJSON()
	}

}
func (c *DrugController) Rank() {
	key := "drug-phb"
	models.Rdb.ZCard(key).Val()
	ranks, err := models.Rdb.ZRevRangeWithScores(key, 0, 10-1).Result()
	if err != nil {
		c.Data["json"] = JsonR{
			Code: 0,
			Msg:  "展示失败",
			Data: nil,
		}
		c.ServeJSON()
		return
	} else {
		c.Data["json"] = JsonR{
			Code: 200,
			Msg:  "展示成功",
			Data: ranks,
		}
		c.ServeJSON()
	}
}
func (c *DrugController) Update() {
	id, _ := c.GetInt("id")
	sex := c.GetString("sex")
	drug := models.Drug{
		Model: gorm.Model{ID: uint(id)},
		Sex:   sex,
	}
	err := models.DB.Where("id=?", id).Updates(&drug).Error
	if err != nil {
		c.Data["json"] = JsonR{
			Code: 0,
			Msg:  "修改失败",
			Data: nil,
		}
		c.ServeJSON()
	} else {
		c.Data["json"] = JsonR{
			Code: 200,
			Msg:  "修改成功",
			Data: drug,
		}
		c.ServeJSON()
	}

}
